<template>
  <div class="inventory-adjustment-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>生产库存调整</span>
          <el-button type="primary" @click="handleCreate">新建调整单</el-button>
        </div>
      </template>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="调整单号">
          <el-input v-model="queryForm.adjustNo" placeholder="请输入调整单号" />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select
            v-model="queryForm.warehouse"
            placeholder="请选择仓库"
            clearable
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调整类型">
          <el-select v-model="queryForm.type" placeholder="请选择调整类型">
            <el-option label="数量调整" value="quantity" />
            <el-option label="库位调整" value="location" />
            <el-option label="状态调整" value="status" />
            <el-option label="批次调整" value="batch" />
          </el-select>
        </el-form-item>
        <el-form-item label="调整日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态">
            <el-option label="待审核" value="pending" />
            <el-option label="已审核" value="approved" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.items" border>
              <el-table-column prop="materialCode" label="物料编码" />
              <el-table-column prop="materialName" label="物料名称" />
              <el-table-column prop="specification" label="规格型号" />
              <el-table-column prop="unit" label="单位" />
              <el-table-column prop="beforeAdjust" label="调整前">
                <template #default="scope">
                  <div v-if="props.row.type === 'quantity'">
                    数量：{{ scope.row.beforeQuantity }}
                  </div>
                  <div v-if="props.row.type === 'location'">
                    库位：{{ scope.row.beforeWarehouse }} -
                    {{ scope.row.beforeLocation }}
                  </div>
                  <div v-if="props.row.type === 'status'">
                    状态：{{ scope.row.beforeStatus }}
                  </div>
                  <div v-if="props.row.type === 'batch'">
                    批次：{{ scope.row.beforeBatch }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="afterAdjust" label="调整后">
                <template #default="scope">
                  <div v-if="props.row.type === 'quantity'">
                    数量：{{ scope.row.afterQuantity }}
                  </div>
                  <div v-if="props.row.type === 'location'">
                    库位：{{ scope.row.afterWarehouse }} -
                    {{ scope.row.afterLocation }}
                  </div>
                  <div v-if="props.row.type === 'status'">
                    状态：{{ scope.row.afterStatus }}
                  </div>
                  <div v-if="props.row.type === 'batch'">
                    批次：{{ scope.row.afterBatch }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="reason" label="调整原因" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="adjustNo" label="调整单号" width="180" />
        <el-table-column prop="warehouse" label="仓库" width="120" />
        <el-table-column prop="type" label="调整类型" width="100">
          <template #default="scope">
            {{ getTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="adjustDate" label="调整日期" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleEdit(scope.row)"
              v-if="scope.row.status === 'pending'"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleApprove(scope.row)"
              v-if="scope.row.status === 'pending'"
              >审核</el-button
            >
            <el-button
              link
              type="success"
              @click="handleExecute(scope.row)"
              v-if="scope.row.status === 'approved'"
              >执行调整</el-button
            >
            <el-button link type="primary" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              link
              type="danger"
              @click="handleCancel(scope.row)"
              v-if="scope.row.status === 'pending'"
              >取消</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建调整单' : '编辑调整单'"
      width="80%"
    >
      <el-form :model="form" label-width="100px" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse">
              <el-select
                v-model="form.warehouse"
                placeholder="请选择仓库"
                @change="handleWarehouseSelect"
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调整类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择调整类型"
                @change="handleTypeChange"
              >
                <el-option label="数量调整" value="quantity" />
                <el-option label="库位调整" value="location" />
                <el-option label="状态调整" value="status" />
                <el-option label="批次调整" value="batch" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="调整日期" prop="adjustDate">
              <el-date-picker
                v-model="form.adjustDate"
                type="date"
                placeholder="请选择调整日期"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-table :data="form.items" border>
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="materialCode" label="物料编码" width="150">
            <template #default="scope">
              <el-select
                v-model="scope.row.materialCode"
                filterable
                remote
                placeholder="请选择物料"
                :remote-method="handleMaterialSearch"
                :loading="materialLoading"
                @change="(value) => handleMaterialSelect(value, scope.$index)"
              >
                <el-option
                  v-for="item in materialOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称" />
          <el-table-column prop="specification" label="规格型号" />
          <el-table-column prop="unit" label="单位" width="80" />

          <!-- 数量调整 -->
          <template v-if="form.type === 'quantity'">
            <el-table-column
              prop="beforeQuantity"
              label="当前数量"
              width="120"
            />
            <el-table-column
              prop="afterQuantity"
              label="调整后数量"
              width="120"
            >
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.afterQuantity"
                  :min="0"
                  @change="handleQuantityChange(scope.row)"
                />
              </template>
            </el-table-column>
          </template>

          <!-- 库位调整 -->
          <template v-if="form.type === 'location'">
            <el-table-column label="当前库位" width="200">
              <template #default="scope">
                {{ scope.row.beforeWarehouse }} - {{ scope.row.beforeLocation }}
              </template>
            </el-table-column>
            <el-table-column label="调整后库位" width="250">
              <template #default="scope">
                <el-select
                  v-model="scope.row.afterWarehouse"
                  placeholder="请选择仓库"
                  @change="
                    (value) => handleAdjustWarehouseSelect(value, scope.$index)
                  "
                >
                  <el-option
                    v-for="item in warehouseOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-select
                  v-model="scope.row.afterLocation"
                  placeholder="请选择库位"
                  :disabled="!scope.row.afterWarehouse"
                >
                  <el-option
                    v-for="item in locationOptions[scope.$index] || []"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
          </template>

          <!-- 状态调整 -->
          <template v-if="form.type === 'status'">
            <el-table-column prop="beforeStatus" label="当前状态" width="120" />
            <el-table-column prop="afterStatus" label="调整后状态" width="120">
              <template #default="scope">
                <el-select
                  v-model="scope.row.afterStatus"
                  placeholder="请选择状态"
                >
                  <el-option label="正常" value="normal" />
                  <el-option label="锁定" value="locked" />
                  <el-option label="冻结" value="frozen" />
                </el-select>
              </template>
            </el-table-column>
          </template>

          <!-- 批次调整 -->
          <template v-if="form.type === 'batch'">
            <el-table-column prop="beforeBatch" label="当前批次" width="120" />
            <el-table-column prop="afterBatch" label="调整后批次" width="200">
              <template #default="scope">
                <el-input
                  v-model="scope.row.afterBatch"
                  placeholder="请输入批次号"
                />
                <el-date-picker
                  v-model="scope.row.manufactureDate"
                  type="date"
                  placeholder="生产日期"
                />
                <el-date-picker
                  v-model="scope.row.expiryDate"
                  type="date"
                  placeholder="有效期至"
                />
              </template>
            </el-table-column>
          </template>

          <el-table-column prop="reason" label="调整原因" min-width="200">
            <template #default="scope">
              <el-input
                v-model="scope.row.reason"
                placeholder="请输入调整原因"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" width="80" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="danger"
                @click="handleRemoveItem(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="table-operations">
          <el-button type="primary" @click="handleAddItem">添加物料</el-button>
        </div>

        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// ... 状态定义和方法实现 ...

// 类型转换
const getTypeText = (type) => {
  const map = {
    quantity: "数量调整",
    location: "库位调整",
    status: "状态调整",
    batch: "批次调整",
  };
  return map[type] || type;
};

// 状态转换
const getStatusType = (status) => {
  const map = {
    pending: "warning",
    approved: "success",
    completed: "success",
    cancelled: "info",
  };
  return map[status] || "info";
};

const getStatusText = (status) => {
  const map = {
    pending: "待审核",
    approved: "已审核",
    completed: "已完成",
    cancelled: "已取消",
  };
  return map[status] || status;
};

// 查询方法
const handleSearch = () => {
  // 实现查询逻辑
};

const handleReset = () => {
  queryForm.adjustNo = "";
  queryForm.warehouse = "";
  queryForm.type = "";
  queryForm.dateRange = [];
  queryForm.status = "";
  handleSearch();
};

// 新建/编辑方法
const handleCreate = () => {
  dialogType.value = "create";
  form.warehouse = "";
  form.type = "";
  form.adjustDate = "";
  form.items = [];
  form.remark = "";
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogType.value = "edit";
  Object.assign(form, row);
  dialogVisible.value = true;
};

// 物料选择
const handleMaterialSearch = async (query) => {
  if (query) {
    materialLoading.value = true;
    try {
      // 实现物料搜索逻辑
      // materialOptions.value = await searchMaterials(query)
    } finally {
      materialLoading.value = false;
    }
  } else {
    materialOptions.value = [];
  }
};

const handleMaterialSelect = async (value, index) => {
  // 加载物料详情和库存信息
  const material = materialOptions.value.find((item) => item.value === value);
  if (material) {
    form.items[index] = {
      ...form.items[index],
      materialName: material.label,
      specification: material.specification,
      unit: material.unit,
      // 加载当前库存信息
    };
  }
};

// 提交方法
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    if (form.items.length === 0) {
      ElMessage.warning("请添加调整物料");
      return;
    }

    // 验证数据
    const valid = form.items.every((item) => {
      if (!item.materialCode) {
        ElMessage.warning("请选择物料");
        return false;
      }
      if (!item.reason) {
        ElMessage.warning("请输入调整原因");
        return false;
      }

      if (form.type === "quantity" && !item.afterQuantity) {
        ElMessage.warning("请输入调整后数量");
        return false;
      }

      if (
        form.type === "location" &&
        (!item.afterWarehouse || !item.afterLocation)
      ) {
        ElMessage.warning("请选择调整后库位");
        return false;
      }

      if (form.type === "status" && !item.afterStatus) {
        ElMessage.warning("请选择调整后状态");
        return false;
      }

      if (form.type === "batch" && !item.afterBatch) {
        ElMessage.warning("请输入调整后批次");
        return false;
      }

      return true;
    });

    if (!valid) return;

    // 实现保存逻辑
    ElMessage.success(dialogType.value === "create" ? "创建成功" : "更新成功");
    dialogVisible.value = false;
    handleSearch();
  } catch (error) {
    console.log("表单验证失败", error);
  }
};

// 审核方法
const handleApprove = (row) => {
  ElMessageBox.confirm("确认审核通过该调整单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现审核逻辑
    ElMessage.success("审核成功");
    handleSearch();
  });
};

// 执行调整
const handleExecute = (row) => {
  ElMessageBox.confirm("确认执行生产库存调整？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现调整逻辑
    ElMessage.success("调整成功");
    handleSearch();
  });
};

// 取消方法
const handleCancel = (row) => {
  ElMessageBox.confirm("确认取消该调整单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 实现取消逻辑
    ElMessage.success("已取消");
    handleSearch();
  });
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};
</script>

<style scoped>
.inventory-adjustment-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.table-operations {
  margin: 20px 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-20 {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
